import "package:ducafe_ui_core/ducafe_ui_core.dart";
import "package:flutter/material.dart";
import "package:flutter_mobx/flutter_mobx.dart";
import "package:go_router/go_router.dart";
import "package:hinge/common/index.dart";
import "package:hinge/store/root_store.dart";
import "package:hinge/common/widgets/custom_dialog.dart";
import "package:hinge/common/widgets/share_bottom_sheet.dart";

class DetailPage extends StatefulWidget {
  final String perfumeId;

  const DetailPage({super.key, required this.perfumeId});

  @override
  State<DetailPage> createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  final _rootStore = RootStore();
  late String _perfumeId;
  late PerfumeModel? _perfume;

  @override
  void initState() {
    super.initState();
    _perfumeId = widget.perfumeId;
    _rootStore.detailStore.loadPerfumeDetail(_perfumeId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Observer(
        builder: (_) {
          if (_rootStore.detailStore.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }

          final perfume = _rootStore.detailStore.currentPerfume;

          // 保存香水信息到实例变量
          _perfume = perfume;

          if (perfume == null) {
            return const Center(child: Text('Perfume not found'));
          }

          // 获取香水所属用户
          final user = UserService.getUserById(perfume.userId);

          return Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [const Color(0xFFC4B4FD), const Color(0xFFEFE0FF)],
              ),
            ),
            child: SafeArea(
              bottom: false,
              top: false,
              child: Container(
                decoration: BoxDecoration(color: Colors.white),
                child: Column(
                  children: [
                    // 顶部香水图片
                    Container(
                      height: 508.h,
                      width: double.infinity,
                      padding: EdgeInsets.symmetric(horizontal: 20.h),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(30.r),
                        image: DecorationImage(
                          image: AssetImage(perfume.url),
                          fit: BoxFit.cover,
                        ),
                      ),
                      child: Padding(
                        padding: EdgeInsets.only(top: 71.h),
                        child:
                            Row(
                              children: [
                                GestureDetector(
                                  onTap: () => Navigator.pop(context),
                                  child: Icon(
                                    IconFont.back,
                                    size: 28.sp,
                                    color: Colors.white,
                                  ),
                                ),
                                SizedBox(width: 10.w),
                                Text(
                                  'Details',
                                  style: TextStyle(
                                    fontSize: 20.sp,
                                    fontWeight: FontWeight.w600,
                                    color: Colors.white,
                                  ),
                                ),
                                Spacer(),
                                GestureDetector(
                                  onTap: () {
                                    showReportBottomSheet(context);
                                  },
                                  child: Icon(
                                    IconFont.report,
                                    size: 28.sp,
                                    color: Colors.white,
                                  ),
                                ),
                              ],
                            ).alignTop(),
                      ),
                    ),

                    // 香水信息
                    Container(
                      width: double.infinity,
                      padding: EdgeInsets.symmetric(
                        horizontal: 20.w,
                        vertical: 20.h,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.9),
                        borderRadius: BorderRadius.circular(24.r),
                      ),
                      child: SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              perfume.title,
                              style: TextStyle(
                                fontSize: 20.sp,
                                fontWeight: FontWeight.w600,
                                color: Color(0xFF2D1457),
                              ),
                            ),
                            SizedBox(height: 12.h),
                            Text(
                              perfume.description,
                              style: TextStyle(
                                fontSize: 15.sp,
                                color: Colors.black87,
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                            SizedBox(height: 20.h),
                          ],
                        ),
                      ),
                    ),

                    Spacer(),

                    _buildUserInteraction(user),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildUserInteraction(UserModel? user) {
    // 获取当前登录用户
    final currentUser = UserService.getCurrentUser();
    // 判断是否为当前用户自己的内容
    final isOwnContent =
        user != null && currentUser != null && user.id == currentUser.id;

    return Container(
      height: 114.h,
      decoration: BoxDecoration(
        color: Color(0xFFF3E5FF),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30.r),
          topRight: Radius.circular(30.r),
        ),
      ),
      child:
          isOwnContent
              ? _buildDeleteButton()
              : Row(
                children: [
                  SizedBox(width: 29.w),
                  GestureDetector(
                    onTap: () {
                      // 只有在用户不为空时才跳转
                      if (user != null) {
                        // 如果是当前用户，直接跳转到个人中心
                        final currentUser = UserService.getCurrentUser();
                        if (currentUser != null && user.id == currentUser.id) {
                          context.push('/personal');
                        } else {
                          // 否则跳转到指定用户的个人中心
                          context.push('/personal/${user.id}');
                        }
                      }
                    },
                    child: Row(
                      children: [
                        CircleAvatar(
                          radius: 22.r,
                          backgroundImage:
                              user != null ? AssetImage(user.avatar) : null,
                        ),
                        SizedBox(width: 12.w),
                        Text(
                          user?.nickname ?? 'Unknown',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w600,
                            color: Colors.black,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Spacer(),
                  Observer(
                    builder: (_) {
                      final isLiked = _rootStore.detailStore.isLiked;
                      return _buildActionButtonWithAnimation(
                        isLiked ? IconFont.likeFill : IconFont.like,
                        isLiked ? Color(0xFFDF6CCB) : Colors.white,
                        "like_$isLiked",
                        onTap: () => _handleLike(),
                      );
                    },
                  ),
                  Observer(
                    builder: (_) {
                      final isCollected = _rootStore.detailStore.isCollected;
                      return _buildActionButtonWithAnimation(
                        isCollected ? IconFont.goodFill : IconFont.good,
                        isCollected ? Color(0xFFDF6CCB) : Colors.white,
                        "collect_$isCollected",
                        onTap: () => _handleCollect(),
                      );
                    },
                  ),
                  _buildActionButton(
                    IconFont.share,
                    Colors.white,
                    onTap: () => _handleShare(),
                  ),
                  SizedBox(width: 16.w),
                ],
              ),
    );
  }

  // 删除按钮
  Widget _buildDeleteButton() {
    return Center(
      child: GestureDetector(
        onTap: () {
          final perfumeId = widget.perfumeId;
          _rootStore.detailStore.deletePerfume(perfumeId).then((_) {
            // 删除后返回上一页
            Navigator.pop(context);
          });
        },
        child: Container(
          width: 352.w,
          height: 60.h,
          decoration: ShapeDecoration(
            color: Color(0xFFBD88FF),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(30.r),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Delete details',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 带动画效果的操作按钮
  Widget _buildActionButtonWithAnimation(
    IconData icon,
    Color bgColor,
    String keyValue, {
    VoidCallback? onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 44.w,
        height: 44.w,
        margin: EdgeInsets.only(right: 8.w),
        decoration: BoxDecoration(
          color: bgColor,
          shape: BoxShape.circle,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: AnimatedSwitcher(
          duration: const Duration(milliseconds: 300),
          transitionBuilder: (child, animation) {
            return ScaleTransition(scale: animation, child: child);
          },
          child: Icon(
            icon,
            key: ValueKey<String>(keyValue),
            size: 24.sp,
            color: bgColor == Colors.white ? Colors.black : Colors.white,
          ),
        ),
      ),
    );
  }

  // 操作按钮
  Widget _buildActionButton(
    IconData icon,
    Color bgColor, {
    VoidCallback? onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 44.w,
        height: 44.w,
        margin: EdgeInsets.only(right: 8.w),
        decoration: BoxDecoration(
          color: bgColor,
          shape: BoxShape.circle,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Icon(
          icon,
          size: 24.sp,
          color: bgColor == Colors.white ? Colors.black : Colors.white,
        ),
      ),
    );
  }

  // 处理点赞操作
  void _handleLike() async {
    if (_perfume == null) return;
    final currentUser = UserService.getCurrentUser();
    if (currentUser == null || UserService.isGuestUser()) {
      _showLoginRequiredDialog('Like');
      return;
    }
    await _rootStore.detailStore.likePerfume();
  }

  // 处理收藏操作
  void _handleCollect() async {
    if (_perfume == null) return;
    final currentUser = UserService.getCurrentUser();
    if (currentUser == null || UserService.isGuestUser()) {
      _showLoginRequiredDialog('Collect');
      return;
    }
    await _rootStore.detailStore.collectPerfume();
  }

  // 处理分享操作
  void _handleShare() {
    if (_perfume == null) return;

    final currentUser = UserService.getCurrentUser();
    if (currentUser == null || UserService.isGuestUser()) {
      _showLoginRequiredDialog('share');
      return;
    }

    // 显示分享弹窗
    showShareBottomSheet(
      context: context,
      content: _perfume, // 传递香水数据
      isVideo: false, // 这是香水详情而非视频
    );
  }

  // 显示登录提示对话框
  void _showLoginRequiredDialog(String action) {
    CustomDialog.show(
      context: context,
      title: 'Login Required',
      content:
          'You need to login to $action this item. Would you like to login now?',
      cancelText: 'Cancel',
      confirmText: 'Login',
      onConfirm: () {
        // 跳转到登录页面，并在返回时刷新页面状态
        context.push('/login').then((_) {
          // 检查用户是否已登录，如果已登录则刷新页面状态
          final currentUser = UserService.getCurrentUser();
          if (currentUser != null && !UserService.isGuestUser()) {
            // 重新加载香水详情，包括用户的点赞和收藏状态
            _rootStore.detailStore.loadPerfumeDetail(_perfumeId);
          }
        });
      },
    );
  }
}
